package org.grottarossa.ui.core.container;


import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;

import org.grottarossa.template.data.Tree;
import org.grottarossa.template.data.pojo.discussions.Discussion;
import org.grottarossa.template.drivers.components.tokens.DiscussionManagementId;
import org.grottarossa.ui.DateHelper;
import org.grottarossa.ui.core.i18n.DM;

import com.vaadin.data.util.HierarchicalContainer;

public class DiscussionContainer extends HierarchicalContainer implements Serializable
{
	private static ResourceBundle m_localizer = DM.instance().getBundle(DiscussionContainer.class.getName());
	Tree<Discussion> tree;
	public Object prec;

	private String MODIFIEDBY = m_localizer.getString("container.columns.modifiedby");
	private String BODY = m_localizer.getString("container.columns.body");
	private String MODIFIEDDATE = m_localizer.getString("container.columns.modifieddate");
	private String TITLE = m_localizer.getString("container.columns.title");

	private String [] m_visibleColumns = { MODIFIEDBY, TITLE, BODY, MODIFIEDDATE };

	private void setDiscussion(Discussion discussion)
	{
		Object obj = addItem();
		Tree<Discussion> discussionTree = tree.getTree(discussion);

		if(discussion.getParentId().getIdentity() != null)
			setParent(obj, prec);
		else
			setParent(obj, null);

		if(discussion.getReplies()==0)
			setChildrenAllowed(obj,false);

		discussion.getModifiedDateTime();

		getContainerProperty(obj, MODIFIEDBY).setValue(discussion.getModifiedBy());
		getContainerProperty(obj, TITLE).setValue(discussion.getName());
		GregorianCalendar calendar = (GregorianCalendar)discussion.getModifiedDateTime();
        getContainerProperty(obj, MODIFIEDDATE).setValue(DateHelper.DateToString(calendar.getTime()) );
		getContainerProperty(obj, BODY).setValue(discussion.getBody());
		getContainerProperty(obj, "id").setValue(discussion.getId());

		for (Tree<Discussion> child : discussionTree.getLeafs())
		{
			prec = obj;
			setDiscussion(child.getHead());
		}
	}

	public DiscussionContainer(HashMap<String, Tree<Discussion>> discussionTrees)
	{
		addContainerProperty(TITLE, String.class, null);
		addContainerProperty(MODIFIEDBY, String.class, null);
		addContainerProperty(MODIFIEDDATE, String.class, null);
		addContainerProperty(BODY, String.class, null);
		addContainerProperty("id", DiscussionManagementId.class, null);

		for (Iterator it=discussionTrees.entrySet().iterator(); it.hasNext(); )
		{
			Map.Entry entry = (Map.Entry)it.next();
			String key = (String)entry.getKey();
			tree = discussionTrees.get(key);
			setDiscussion( tree.getHead());
		}
	}

	public String[] getVisibleColumns()
	{
		return m_visibleColumns;
	}
}
